package wowraidmanager.client.auction.admin.maintain;

import java.util.ArrayList;
import java.util.Date;

import wowraidmanager.client.BaseComposite;
import wowraidmanager.client.service.auction.AuctionListService;
import wowraidmanager.client.service.auction.AuctionListServiceAsync;
import wowraidmanager.client.service.auction.CheckItemListService;
import wowraidmanager.client.service.auction.CheckItemListServiceAsync;
import wowraidmanager.client.service.auction.RealmListService;
import wowraidmanager.client.service.auction.RealmListServiceAsync;
import wowraidmanager.shared.model.auction.AuctionList;
import wowraidmanager.shared.model.auction.CheckItemList;
import wowraidmanager.shared.model.auction.RealmList;
import wowraidmanager.shared.model.auction.json.Auction;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

public class AdminAuctionItemList extends BaseComposite{

    private static AuctionItemListUiBinder uiBinder = GWT.create(AuctionItemListUiBinder.class);

    static int COLUMN_CHECKITEM_ITEMNAME = 0;
    static int COLUMN_CHECKITEM_CHECKBUTTON = 1;

    static int COLUMN_AUCTION_AUC = 1;
    static int COLUMN_AUCTION_OWNER = 2;
    static int COLUMN_AUCTION_ITEM = 3;
    static int COLUMN_AUCTION_BID = 4;
    static int COLUMN_AUCTION_BUYOUT = 5;
    static int COLUMN_AUCTION_QUANTITY = 6;
    static int COLUMN_AUCTION_TIMELEFT = 7;

    static DateTimeFormat DATE_FORMAT =DateTimeFormat.getFormat("yyyy/MM/dd");
    static Date DATE_NOW = new Date();
    static Date DATE_YESTARDAY = new Date(System.currentTimeMillis() - (24 * 60 * 60 * 1000));
    static Date DATE_WEEK = new Date(System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000));
    static Date DATE_MONTH = new Date(System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000)- (7 * 24 * 60 * 60 * 1000)- (7 * 24 * 60 * 60 * 1000)- (7 * 24 * 60 * 60 * 1000)- (2 * 24 * 60 * 60 * 1000));

    protected CheckItemListServiceAsync checkItemListService = GWT.create(CheckItemListService.class);

    protected RealmListServiceAsync realmListService = GWT.create(RealmListService.class);

    protected AuctionListServiceAsync auctionListService = GWT.create(AuctionListService.class);

    interface AuctionItemListUiBinder extends UiBinder<Widget, AdminAuctionItemList>{
    }


    ArrayList<AuctionList> auctionListList;

    ArrayList<RealmList> realmListList;

    ArrayList<CheckItemList> checkItemListList;

    ArrayList<AuctionList> allianceAuctionListList;
    ArrayList<AuctionList> hordeAuctionListList;
    ArrayList<AuctionList> neutralAuctionListList;

    @UiField
    HTMLPanel dataPanel;

    @UiField
    HTMLPanel loadPanel;

    @UiField
    ListBox realmListListBox;

    @UiField
    ListBox typeListBox;

    @UiField
    Label serverLabel;

    @UiField
    HTML itemNameHTML;

    @UiField
    FlexTable checkItemListFlexTable;

    @UiField
    ListBox selectDateListBox;

    @UiField
    ListBox selectRegionListBox;

    @UiField
    FlexTable auctionItemListFlexTable;

    public AdminAuctionItemList(){
        initWidget(uiBinder.createAndBindUi(this));
        getRealmListData();
    }

    private void setWidget(){
        setListBox();
        setcheckItemListFlexTable(checkItemListList);
        setPanelVisible();
    }

    private void setPanelVisible(){
        dataPanel.setVisible(true);

        loadPanel.setVisible(false);
    }

    private void setcheckItemListFlexTable(ArrayList<CheckItemList> selectCheckItemListList){

        int row = 0;

        checkItemListFlexTable.removeAllRows();
        checkItemListFlexTable.setText(row, COLUMN_CHECKITEM_ITEMNAME, "ItemName");
        checkItemListFlexTable.setText(row, COLUMN_CHECKITEM_CHECKBUTTON, "PriceCheck");

        row++;
        for(CheckItemList checkItemList:selectCheckItemListList){
            String html = "<a href=\"http://www.wowhead.com/item=" + checkItemList.getItemId() + "\" target=\"_blank\" class=\"q" + checkItemList.getColorId() + "\">[" + checkItemList.getItemName() + "]</a>";
            checkItemListFlexTable.setHTML(row, COLUMN_CHECKITEM_ITEMNAME, html);
            checkItemListFlexTable.getCellFormatter().addStyleName(row, COLUMN_CHECKITEM_ITEMNAME, "itemlink");


            Button checkPriceButton = new Button("PriceCheck");
            setPriceButton(checkPriceButton, checkItemList);
            checkItemListFlexTable.setWidget(row, COLUMN_CHECKITEM_CHECKBUTTON, checkPriceButton);

            row++;
        }
    }

    private void setPriceButton(Button checkPriceButton, final CheckItemList checkItemList){
        checkPriceButton.addClickHandler(new ClickHandler(){

            public void onClick(ClickEvent event){
                setPriceCheck(checkItemList);
            }
        });
    }

    protected void setPriceCheck(CheckItemList checkItemList){
        String realmName = realmListListBox.getItemText(realmListListBox.getSelectedIndex());
        getAuctionListData(checkItemList, realmName);
    }

    private void setSelectItemFlexTable(CheckItemList checkItemList, String realmName){
        String updateTime = "";
        for(RealmList realmList:realmListList){
            if(realmList.getRealm().equals(realmName)){
                updateTime = DateTimeFormat.getFormat("yyyy/MM/dd HH:mm").format(realmList.getUpdateTime());
            }
        }
        serverLabel.setText(realmName + " UpdateTime:" + updateTime);
        itemNameHTML.setHTML("<a href=\"http://www.wowhead.com/item=" + checkItemList.getItemId() + "\" target=\"_blank\" class=\"q" + checkItemList.getColorId() + "\">[" + checkItemList.getItemName() + "]</a>");
        allianceAuctionListList = new ArrayList<AuctionList>();
        hordeAuctionListList = new ArrayList<AuctionList>();
        neutralAuctionListList = new ArrayList<AuctionList>();
        for(AuctionList auctionList:auctionListList){
            if(auctionList.getItemId().equals(checkItemList.getItemId()) && auctionList.getRealm().equals(realmName)){
                String region = auctionList.getRegion();
                if(region.equals("alliance")){
                    allianceAuctionListList.add(auctionList);
                }else if(region.equals("horde")){
                    hordeAuctionListList.add(auctionList);
                }else if(region.equals("neutral")){
                    neutralAuctionListList.add(auctionList);
                }
            }
        }

        ArrayList<String> selectDateList = new ArrayList<String>();
        selectDateList = setSelectDateList(allianceAuctionListList, selectDateList);
        selectDateList = setSelectDateList(hordeAuctionListList, selectDateList);
        selectDateList = setSelectDateList(neutralAuctionListList, selectDateList);

        setSelectListBox(selectDateList);
        checkSelectListBox();
    }

    private void setSelectListBox(ArrayList<String> selectDateList){
        selectDateListBox.clear();
        for(String dateString:selectDateList){
            selectDateListBox.addItem(dateString);
        }

        selectRegionListBox.clear();
        selectRegionListBox.addItem("Alliance");
        selectRegionListBox.addItem("Horde");
        selectRegionListBox.addItem("Neutral");

        selectDateListBox.addChangeHandler(new ChangeHandler(){

            public void onChange(ChangeEvent event){
                checkSelectListBox();
            }
        });

        selectRegionListBox.addChangeHandler(new ChangeHandler(){

            public void onChange(ChangeEvent event){
                checkSelectListBox();
            }
        });
    }

    protected void checkSelectListBox(){
        if(selectDateListBox.getItemCount() < 1){
            return;
        }
        String selectDate = selectDateListBox.getItemText(selectDateListBox.getSelectedIndex());
        String selectRegion = selectRegionListBox.getItemText(selectRegionListBox.getSelectedIndex());

        if(selectRegion.equals("Alliance")){
            setAuctionItemFlexTable(allianceAuctionListList, selectDate);
        }else if(selectRegion.equals("Horde")){
            setAuctionItemFlexTable(hordeAuctionListList, selectDate);
        }else if(selectRegion.equals("Neutral")){
            setAuctionItemFlexTable(neutralAuctionListList, selectDate);
        }
    }

    private void setAuctionItemFlexTable(ArrayList<AuctionList> auctionListList, String selectDate){
        ArrayList<AuctionList> selectAuctionListList = new ArrayList<AuctionList>();

        for(AuctionList auctionList:auctionListList){
            if(DATE_FORMAT.format(auctionList.getDate()).equals(selectDate)){
                selectAuctionListList.add(auctionList);
            }
        }

        int row = 0;
        auctionItemListFlexTable.removeAllRows();

        for(AuctionList auctionList:selectAuctionListList){
            for(Auction auction:auctionList.getAuctionData()){
                auctionItemListFlexTable.setText(row, COLUMN_AUCTION_AUC, auction.getAuc());
                auctionItemListFlexTable.setText(row, COLUMN_AUCTION_OWNER, auction.getOwner());
                auctionItemListFlexTable.setText(row, COLUMN_AUCTION_ITEM, auction.getItem());
                auctionItemListFlexTable.setText(row, COLUMN_AUCTION_BID, auction.getBid());
                auctionItemListFlexTable.setText(row, COLUMN_AUCTION_BUYOUT, auction.getBuyout());
                auctionItemListFlexTable.setText(row, COLUMN_AUCTION_QUANTITY, auction.getQuantity());
                auctionItemListFlexTable.setText(row, COLUMN_AUCTION_TIMELEFT, auction.getTimeLeft());
                row++;
            }
        }
    }

    private ArrayList<String> setSelectDateList(ArrayList<AuctionList> auctionListList, ArrayList<String> selectDateList){

        for(AuctionList auctionList:auctionListList){
            if(!selectDateList.contains(DATE_FORMAT.format(auctionList.getDate()))){
                selectDateList.add(DATE_FORMAT.format(auctionList.getDate()));
            }
        }

        return selectDateList;
    }

    protected void setListBox(){
        for(RealmList realmlist:realmListList){
            realmListListBox.addItem(realmlist.getRealm());
        }

        ArrayList<String> typeList = new ArrayList<String>();

        for(CheckItemList checkItemList:checkItemListList){
            if(!typeList.contains(checkItemList.getType())){
                typeList.add(checkItemList.getType());
            }
        }

        typeListBox.addItem("All");

        for(String type:typeList){
            typeListBox.addItem(type);
        }

        typeListBox.addChangeHandler(new ChangeHandler(){

            public void onChange(ChangeEvent event){
                selectType();

            }
        });
    }

    protected void selectType(){
        String type = typeListBox.getItemText(typeListBox.getSelectedIndex());

        if(type.equals("All")){
            setcheckItemListFlexTable(checkItemListList);
        }else{
            ArrayList<CheckItemList> selectCheckItemListList = new ArrayList<CheckItemList>();
            for(CheckItemList checkItemList:checkItemListList){
                if(type.equals(checkItemList.getType())){
                    selectCheckItemListList.add(checkItemList);
                }
            }
            setcheckItemListFlexTable(selectCheckItemListList);
        }
    }

    private void getAuctionListData(final CheckItemList checkItemList, final String realmName){
        auctionListService.getAuctionList(DATE_NOW, DATE_MONTH, checkItemList.getItemId(), realmName, new AsyncCallback<ArrayList<AuctionList>>(){

            public void onSuccess(ArrayList<AuctionList> result){
                auctionListList = result;
                setSelectItemFlexTable(checkItemList, realmName);
            }

            public void onFailure(Throwable caught){
                clearInfoMessage();
                setErrorMessage("AuctionListの取得に失敗しました。");
            }
        });

    }

    protected void getRealmListData(){
        realmListService.getRealmList(new AsyncCallback<ArrayList<RealmList>>(){

            public void onSuccess(ArrayList<RealmList> result){
                realmListList = result;
                getCheckItemListData();
            }

            public void onFailure(Throwable caught){
                clearInfoMessage();
                setErrorMessage("RealmListの取得に失敗しました。");
            }
        });
    }

    protected void getCheckItemListData(){
        checkItemListService.getCheckItemList(new AsyncCallback<ArrayList<CheckItemList>>(){

            public void onSuccess(ArrayList<CheckItemList> result){
                checkItemListList = result;
                setWidget();
            }

            public void onFailure(Throwable caught){
                clearInfoMessage();
                setErrorMessage("CheckItemListの取得に失敗しました。");
            }
        });
    }
}
